<template>
  <div class="system-monitor-container">
    <!-- 页面标题区域 -->
    <div class="page-header-wrapper">
      <div class="page-title-section">
        <h1 class="page-title">系统监控</h1>
        <p class="page-description">实时监控系统资源使用情况、业务指标和租户隔离状态</p>
      </div>
      <div class="page-actions-section">
        <button
          @click="refreshData"
          :disabled="loading"
          class="action-btn primary"
        >
          <i class="fas fa-sync mr-2" :class="{ 'animate-spin': loading }"></i>
          <span>刷新数据</span>
        </button>
        <button
          @click="toggleAutoRefresh"
          :class="autoRefresh ? 'action-btn success' : 'action-btn secondary'"
        >
          <i class="fas fa-play mr-2" v-if="!autoRefresh"></i>
          <i class="fas fa-pause mr-2" v-else></i>
          <span>{{ autoRefresh ? '停止自动刷新' : '自动刷新' }}</span>
        </button>
      </div>
    </div>

    <!-- 系统资源统计卡片 -->
    <div class="metrics-section">
      <h2 class="section-title">系统资源概览</h2>
      <div class="metrics-grid">
        <!-- CPU 使用率 -->
        <div class="metric-card">
          <div class="metric-header">
            <div class="metric-info">
              <p class="metric-label">CPU使用率</p>
              <p class="metric-value">{{ formatPercent(systemInfo?.cpuUsage) }}</p>
              <p class="metric-desc">{{ systemInfo?.cpuCores }} 核心</p>
            </div>
            <div class="metric-icon cpu">
              <i class="fas fa-microchip"></i>
            </div>
          </div>
          <div class="metric-progress">
            <div class="progress-bar">
              <div class="progress-fill cpu-fill" 
                   :style="{ width: `${Math.min(systemInfo?.cpuUsage || 0, 100)}%` }"></div>
            </div>
          </div>
        </div>

        <!-- 内存使用率 -->
        <div class="metric-card">
          <div class="metric-header">
            <div class="metric-info">
              <p class="metric-label">内存使用率</p>
              <p class="metric-value">{{ formatPercent(systemInfo?.memoryUsage) }}</p>
              <p class="metric-desc">{{ formatBytes(systemInfo?.totalMemory) }} 总计</p>
            </div>
            <div class="metric-icon memory">
              <i class="fas fa-memory"></i>
            </div>
          </div>
          <div class="metric-progress">
            <div class="progress-bar">
              <div class="progress-fill memory-fill" 
                   :style="{ width: `${Math.min(systemInfo?.memoryUsage || 0, 100)}%` }"></div>
            </div>
          </div>
        </div>

        <!-- 磁盘使用率 -->
        <div class="metric-card">
          <div class="metric-header">
            <div class="metric-info">
              <p class="metric-label">磁盘使用率</p>
              <p class="metric-value">{{ formatPercent(systemInfo?.diskUsage) }}</p>
              <p class="metric-desc">{{ formatBytes(systemInfo?.totalDisk) }} 总计</p>
            </div>
            <div class="metric-icon disk">
              <i class="fas fa-hdd"></i>
            </div>
          </div>
          <div class="metric-progress">
            <div class="progress-bar">
              <div class="progress-fill disk-fill" 
                   :style="{ width: `${Math.min(systemInfo?.diskUsage || 0, 100)}%` }"></div>
            </div>
          </div>
        </div>

        <!-- 网络吞吐 -->
        <div class="metric-card">
          <div class="metric-header">
            <div class="metric-info">
              <p class="metric-label">网络吞吐</p>
              <p class="metric-value">{{ formatBytes(systemInfo?.networkThroughput) }}/s</p>
              <p class="metric-desc">实时传输速率</p>
            </div>
            <div class="metric-icon network">
              <i class="fas fa-network-wired"></i>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 系统健康状态和业务统计 -->
    <div class="health-business-section">
      <div class="health-panel">
        <h3 class="panel-title">系统健康状态</h3>
        <div class="health-status-grid">
          <div class="health-item">
            <div class="health-icon healthy">
              <i class="fas fa-heartbeat"></i>
            </div>
            <div class="health-info">
              <p class="health-label">整体状态</p>
              <p class="health-value" :class="getHealthStatusClass(systemHealth?.status)">
                {{ systemHealth?.status || 'UNKNOWN' }}
              </p>
            </div>
          </div>
          
          <div class="health-item">
            <div class="health-icon">
              <i class="fas fa-clock"></i>
            </div>
            <div class="health-info">
              <p class="health-label">运行时间</p>
              <p class="health-value">{{ formatUptime(systemInfo?.uptime) }}</p>
            </div>
          </div>
          
          <div class="health-item">
            <div class="health-icon">
              <i class="fas fa-thermometer-half"></i>
            </div>
            <div class="health-info">
              <p class="health-label">系统负载</p>
              <p class="health-value">{{ systemInfo?.loadAverage?.toFixed(2) }}</p>
            </div>
          </div>
        </div>
      </div>

      <div class="business-panel">
        <h3 class="panel-title">业务统计</h3>
        <div class="business-stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ businessStats?.onlineUsers || 0 }}</div>
            <div class="stat-label">在线用户</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ businessStats?.activeTenants || 0 }}</div>
            <div class="stat-label">活跃租户</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ businessStats?.requestsPerMin || 0 }}</div>
            <div class="stat-label">每分钟请求</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ businessStats?.errorRate?.toFixed(2) || 0 }}%</div>
            <div class="stat-label">错误率</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 租户隔离监控 -->
    <div class="tenant-section" v-if="tenantMetrics">
      <div class="panel">
        <div class="panel-header">
          <h3 class="panel-title">租户隔离监控</h3>
          <div class="status-indicator">
            <div class="status-dot" 
                 :class="tenantMetrics.crossTenantLeakageWarnings.length === 0 ? 'healthy' : 'warning'"></div>
            <span class="status-text">
              {{ tenantMetrics.crossTenantLeakageWarnings.length === 0 ? '隔离正常' : '存在异常' }}
            </span>
          </div>
        </div>
        
        <div class="tenant-stats-grid">
          <!-- 租户缓存分布 -->
          <div class="tenant-stat-item">
            <h4 class="stat-title">租户缓存分布</h4>
            <div class="stat-list">
              <div v-for="[tenantId, count] in Object.entries(tenantMetrics.tenantCacheKeyCount)" 
                   :key="tenantId" class="stat-row">
                <span class="stat-label">{{ tenantId }}</span>
                <span class="stat-value">{{ count }} 键</span>
              </div>
            </div>
          </div>

          <!-- 缓存命中率 -->
          <div class="tenant-stat-item">
            <h4 class="stat-title">缓存命中率</h4>
            <div class="stat-list">
              <div v-for="[tenantId, hitRate] in Object.entries(tenantMetrics.tenantCacheHitRate)" 
                   :key="tenantId" class="stat-row">
                <span class="stat-label">{{ tenantId }}</span>
                <span class="stat-value">{{ formatPercent(hitRate) }}</span>
              </div>
            </div>
          </div>

          <!-- 格式合规性 -->
          <div class="tenant-stat-item">
            <h4 class="stat-title">格式问题</h4>
            <div class="stat-list">
              <div v-for="issue in tenantMetrics.formatCompliance.commonIssues" 
                   :key="issue" class="issue-item">
                {{ issue }}
              </div>
              <div v-if="tenantMetrics.formatCompliance.commonIssues.length === 0" 
                   class="no-issues">
                无格式问题
              </div>
            </div>
          </div>
        </div>

        <!-- 跨租户泄露警告 -->
        <div v-if="tenantMetrics.crossTenantLeakageWarnings.length > 0" class="warning-section">
          <h4 class="warning-title">🚨 跨租户泄露警告</h4>
          <ul class="warning-list">
            <li v-for="warning in tenantMetrics.crossTenantLeakageWarnings" :key="warning">
              • {{ warning }}
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { systemMonitorApi, userStatisticsApi } from '@/api/monitor'

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(false)
let refreshTimer: NodeJS.Timeout | null = null

const systemInfo = ref({
  cpuUsage: 0,
  cpuCores: 0,
  memoryUsage: 0,
  totalMemory: 0,
  diskUsage: 0,
  totalDisk: 0,
  networkThroughput: 0,
  uptime: 0,
  loadAverage: 0
})

const systemHealth = ref({
  status: 'UNKNOWN'
})

const businessStats = ref({
  onlineUsers: 0,
  activeTenants: 0,
  requestsPerMin: 0,
  errorRate: 0
})

const tenantMetrics = ref({
  tenantCacheKeyCount: {},
  tenantCacheHitRate: {},
  formatCompliance: {
    commonIssues: []
  },
  crossTenantLeakageWarnings: []
})

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    // 调用真实API获取系统信息
    const systemResponse = await systemMonitorApi.getSystemInfo()
    if (systemResponse.success && systemResponse.data) {
      const data = systemResponse.data
      systemInfo.value = {
        cpuUsage: data.cpuUsage || 0,
        cpuCores: data.cpuCores || 0,
        memoryUsage: data.memoryUsage || 0,
        totalMemory: data.totalMemory || 0,
        diskUsage: data.diskInfos?.[0]?.usage || 0,
        totalDisk: data.diskInfos?.[0]?.total || 0,
        networkThroughput: 0, // 暂时没有网络统计
        uptime: data.jvmUptime || 0,
        loadAverage: data.cpuUsage || 0
      }
    }

    // ✅ 调用正确的用户统计API（已迁移）
    const businessResponse = await userStatisticsApi.getBusinessStatistics()
    if (businessResponse.success && businessResponse.data) {
      const data = businessResponse.data
      businessStats.value = {
        onlineUsers: data.onlineUsers || 0,
        activeTenants: data.tenantStats?.activeTenants || 0,
        requestsPerMin: 0, // 暂时没有API调用统计
        errorRate: 0 // 暂时没有错误率统计
      }
    }

    // 调用真实API获取租户隔离指标
    const tenantResponse = await systemMonitorApi.getTenantIsolationMetrics()
    if (tenantResponse.success && tenantResponse.data) {
      const data = tenantResponse.data
      tenantMetrics.value = {
        tenantCacheKeyCount: data.tenantCacheKeyCount || {},
        tenantCacheHitRate: data.tenantCacheHitRate || {},
        formatCompliance: data.formatCompliance || { commonIssues: [] },
        crossTenantLeakageWarnings: data.crossTenantLeakageWarnings || []
      }
    }

    // 调用真实API获取系统健康状态
    const healthResponse = await systemMonitorApi.getSystemHealth()
    if (healthResponse.success && healthResponse.data) {
      systemHealth.value = {
        status: healthResponse.data.status || 'UNKNOWN'
      }
    }

    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('获取监控数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  if (autoRefresh.value) {
    refreshTimer = setInterval(refreshData, 30000)
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }
}

const formatPercent = (value: number) => {
  return `${(value || 0).toFixed(1)}%`
}

const formatBytes = (bytes: number) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`
}

const formatUptime = (seconds: number) => {
  if (!seconds) return '0天'
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  return `${days}天${hours}小时`
}

const getHealthStatusClass = (status: string) => {
  const classes = {
    'HEALTHY': 'text-green-600',
    'WARNING': 'text-yellow-600',
    'CRITICAL': 'text-red-600'
  }
  return classes[status as keyof typeof classes] || 'text-gray-600'
}

onMounted(() => {
  refreshData()
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
/* 页面容器 */
.system-monitor-container {
  padding: 2rem;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  min-height: 100vh;
}

/* 页面标题区域 */
.page-header-wrapper {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 2.5rem;
  margin-bottom: 3rem;
  box-shadow: 
    0 10px 40px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.page-title-section {
  margin-bottom: 2rem;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 0.75rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  font-size: 1.1rem;
  color: #64748b;
  line-height: 1.6;
}

.page-actions-section {
  display: flex;
  gap: 1.25rem;
  flex-wrap: wrap;
}

/* 按钮样式 */
.action-btn {
  padding: 0.75rem 1.5rem;
  border-radius: 12px;
  border: none;
  font-weight: 500;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
  cursor: pointer;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.action-btn.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.action-btn.success {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
}

.action-btn.secondary {
  background: linear-gradient(135deg, #cbd5e0 0%, #a0aec0 100%);
  color: #4a5568;
}

/* 区块标题 */
.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 2rem;
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 2rem;
  background: linear-gradient(to bottom, #667eea, #764ba2);
  border-radius: 2px;
}

/* 统计卡片区域 */
.metrics-section {
  margin-bottom: 4rem;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
}

.metric-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 2rem;
  box-shadow: 
    0 10px 40px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-4px);
  box-shadow: 
    0 20px 60px rgba(0, 0, 0, 0.12),
    0 4px 16px rgba(0, 0, 0, 0.08);
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1.5rem;
}

.metric-info {
  flex: 1;
}

.metric-label {
  font-size: 0.9rem;
  color: #64748b;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.metric-value {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1a202c;
  margin-bottom: 0.25rem;
  line-height: 1;
}

.metric-desc {
  font-size: 0.85rem;
  color: #94a3b8;
}

.metric-icon {
  width: 4rem;
  height: 4rem;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
  margin-left: 1rem;
}

.metric-icon.cpu {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.metric-icon.memory {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.metric-icon.disk {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.metric-icon.network {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.metric-progress {
  margin-top: 1rem;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #f1f5f9;
  border-radius: 8px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 8px;
  transition: width 0.6s ease;
}

.cpu-fill {
  background: linear-gradient(90deg, #667eea, #764ba2);
}

.memory-fill {
  background: linear-gradient(90deg, #f093fb, #f5576c);
}

.disk-fill {
  background: linear-gradient(90deg, #4facfe, #00f2fe);
}

/* 健康状态和业务统计区域 */
.health-business-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2.5rem;
  margin-bottom: 4rem;
}

@media (max-width: 1024px) {
  .health-business-section {
    grid-template-columns: 1fr;
  }
}

.health-panel,
.business-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 2.5rem;
  box-shadow: 
    0 10px 40px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.panel-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 2rem;
}

.health-status-grid {
  display: grid;
  gap: 1.5rem;
}

.health-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 0;
  border-bottom: 1px solid #f1f5f9;
}

.health-item:last-child {
  border-bottom: none;
}

.health-icon {
  width: 3rem;
  height: 3rem;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  color: white;
}

.health-icon.healthy {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
}

.health-info {
  flex: 1;
}

.health-label {
  font-size: 0.9rem;
  color: #64748b;
  margin-bottom: 0.25rem;
}

.health-value {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1a202c;
}

.business-stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.5rem;
}

.stat-item {
  text-align: center;
  padding: 1.5rem;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 0.5rem;
}

.stat-label {
  font-size: 0.9rem;
  color: #64748b;
  font-weight: 500;
}

/* 租户监控区域 */
.tenant-section {
  margin-bottom: 3rem;
}

.panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 2.5rem;
  box-shadow: 
    0 10px 40px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #f1f5f9;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.healthy {
  background: #48bb78;
}

.status-dot.warning {
  background: #ed8936;
}

.status-text {
  font-size: 0.9rem;
  color: #64748b;
}

.tenant-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

.tenant-stat-item {
  padding: 1.5rem;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.stat-title {
  font-size: 1rem;
  font-weight: 600;
  color: #374151;
  margin-bottom: 1rem;
}

.stat-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 0;
  border-bottom: 1px solid rgba(148, 163, 184, 0.2);
}

.stat-row:last-child {
  border-bottom: none;
}

.stat-label {
  font-size: 0.9rem;
  color: #64748b;
}

.stat-value {
  font-size: 0.9rem;
  font-weight: 600;
  color: #1a202c;
}

.issue-item {
  font-size: 0.9rem;
  color: #dc2626;
  padding: 0.5rem 0;
}

.no-issues {
  font-size: 0.9rem;
  color: #059669;
  padding: 0.5rem 0;
}

.warning-section {
  margin-top: 2rem;
  padding: 1.5rem;
  background: linear-gradient(135deg, #fef7f7 0%, #fce8e8 100%);
  border: 1px solid #f87171;
  border-radius: 16px;
}

.warning-title {
  font-size: 1rem;
  font-weight: 600;
  color: #dc2626;
  margin-bottom: 1rem;
}

.warning-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.warning-list li {
  font-size: 0.9rem;
  color: #dc2626;
  padding: 0.25rem 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .system-monitor-container {
    padding: 1rem;
  }
  
  .page-header-wrapper {
    padding: 2rem;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .metrics-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  
  .business-stats-grid {
    grid-template-columns: 1fr;
  }
  
  .tenant-stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
